const dayjs = require('dayjs');
/**
 * 研发项目状态机业务逻辑
 */
// 修复路径问题，使用相对路径而不是多层级路径解析
const projectHelpers = require('../../config/project_helpers_config');
const cloudHelper = projectHelpers.cloudHelper;
const pageHelper = projectHelpers.pageHelper;
const timeHelper = projectHelpers.timeHelper;

// 修复路径问题
let ResearchService;
try {
	ResearchService = require('../../services/research_service.js');
	console.log('研发服务模块导入成功');
} catch (e) {
	console.warn('研发服务模块导入失败:', e);
	// 定义一个模拟的ResearchService类
	ResearchService = class ResearchService {
		async getResearchDetail(projectId) {
			console.log('模拟获取研发项目详情:', projectId);
			return { PROJECT_STATUS: 0, PROJECT_ACTIVE_STATUS: 0 };
		}
		
		async updateResearchStatus(projectId, status, activeStatus, data) {
			console.log('模拟更新研发项目状态:', { projectId, status, activeStatus, data });
			return true;
		}
	};
}
const FlowTaskBiz = require('./flow_task_biz.js');

// 导入角色配置，使用相对路径
const roleConfig = require('../../config/research_role_config.js');
const ResearchStateMachine = require('../../config/research_state_machine.js');

/**
 * 角色模拟配置
 */
const ROLE_SIMULATION = {
	// 是否启用角色模拟
	ENABLED: false,
	
	// 是否只允许管理员使用模拟功能
	ADMIN_ONLY: false,
	
	// 允许模拟的角色列表
	ALLOWED_ROLES: roleConfig.ROLES ? roleConfig.ROLES.map(role => role.id) : [],
	
	// 是否记录模拟操作日志
	LOG_ACTIONS: true
};

/**
 * 项目状态定义
 */
const PROJECT_STATUS = {
	// 基础状态
	PENDING: 0, // 待立项
	REVIEWING: 1, // 项目审核
	DORMANT: 2, // 休眠
	ACTIVE: 3, // 活动
	COMPLETED: 99, // 完成
	
	// 活动子状态
	ACTIVE_HARDWARE_CONFIRM: 10, // 硬件确认
	ACTIVE_HARDWARE_DESIGN: 11, // 硬件设计打样
	ACTIVE_SW_HW_DEBUG: 12, // 软硬件调试
	ACTIVE_TESTING: 13, // 测试验证
	ACTIVE_CUSTOMER_CONFIRM: 14, // 客户确认
	ACTIVE_ORDER_PREPARATION: 15, // 订单准备
	ACTIVE_PRODUCTION: 16, // 生产
	ACTIVE_PRODUCT_FEEDBACK: 17, // 产品待客户反馈
};

/**
 * 活动子状态定义
 */
const ACTIVE_STATUS = {
	// 硬件确认子状态
	HW_CONFIRM_PENDING: 0, // 待确认
	HW_CONFIRM_REVIEWING: 1, // 确认中
	HW_CONFIRM_COMPLETED: 2, // 确认完成
	
	// 硬件设计打样子状态
	HW_DESIGN_DESIGNING: 0, // 设计中
	HW_DESIGN_REVIEWING: 1, // 审核中
	HW_DESIGN_PURCHASING: 2, // 采购打样
	HW_DESIGN_MAKING: 3, // 制样
	HW_DESIGN_STORAGE: 4, // 入库
	
	// 软硬件调试子状态
	DEBUG_DEBUGGING: 0, // 调试中
	DEBUG_ISSUE_FIXING: 1, // 问题修复
	DEBUG_COMPLETED: 2, // 调试完成
	
	// 测试验证子状态
	TESTING_IN_PROGRESS: 0, // 测试中
	TESTING_NO_TEST: 1, // 无测试申请
	TESTING_COMPLETED: 2, // 测试完成
	
	// 客户确认子状态
	CUSTOMER_SHIPPING: 0, // 寄样
	CUSTOMER_TESTING: 1, // 客户测试
	CUSTOMER_NO_SIGN: 2, // 无签样审核
	CUSTOMER_SAMPLE_STORAGE: 3, // 样品入库
	CUSTOMER_ARCHIVING: 4, // 归档
	
	// 订单准备子状态
	ORDER_PENDING: 0, // 待量产
	ORDER_REVIEWING: 1, // 订单审核
	ORDER_DOCS_SENDING: 2, // 文控发送生产资料
	ORDER_DOCS_SUPPLEMENTING: 3, // 研发补充资料
	ORDER_MEETING: 4, // 产前会议
	ORDER_PREPARATION: 5, // 生产准备
	
	// 生产子状态
	PRODUCTION_IN_PROGRESS: 0, // 生产中
	PRODUCTION_PE_ISSUE: 1, // PE问题处理中
	PRODUCTION_RD_ISSUE: 2, // 研发问题排查
	PRODUCTION_COMPLETED: 3, // 生产完成
	
	// 产品待客户反馈子状态
	FEEDBACK_PENDING: 0, // 待反馈
	FEEDBACK_RECEIVED: 1, // 已收到反馈
	FEEDBACK_PROCESSING: 2, // 反馈处理中
	FEEDBACK_RESOLVED: 3, // 反馈已解决
	
	// 项目审核子状态
	REVIEW_DIRECTOR: 1, // 待董事长审核
	REVIEW_MANAGER: 2, // 待研发经理审核
	REVIEW_ASSIGN: 3, // 项目分配
	
	// 休眠子状态
	DORMANT_REVIEW: 1, // 研发审核
	DORMANT_ARCHIVE: 2, // 休眠归档
};

/**
 * 状态与角色权限映射
 * 定义每个状态和子状态允许进行流转的角色
 */
const STATUS_ROLE_PERMISSIONS = {
	// 项目审核状态权限
	[PROJECT_STATUS.REVIEWING]: {
		[ACTIVE_STATUS.REVIEW_DIRECTOR]: ['director'], // 待董事长审核：董事长
		[ACTIVE_STATUS.REVIEW_MANAGER]: ['research_manager'], // 待研发经理审核：研发经理
		[ACTIVE_STATUS.REVIEW_ASSIGN]: ['research_manager'], // 项目分配：研发经理
	},
	
	// 休眠状态权限
	[PROJECT_STATUS.DORMANT]: {
		[ACTIVE_STATUS.DORMANT_REVIEW]: ['research_manager'], // 研发审核：研发经理
		[ACTIVE_STATUS.DORMANT_ARCHIVE]: ['document_controller'], // 休眠归档：文控
	},
	
	// 硬件确认状态权限
	[PROJECT_STATUS.ACTIVE_HARDWARE_CONFIRM]: {
		'all': ['hardware_engineer'] // 全部子状态：硬件工程师
	},
	
	// 硬件设计打样状态权限
	[PROJECT_STATUS.ACTIVE_HARDWARE_DESIGN]: {
		[ACTIVE_STATUS.HW_DESIGN_DESIGNING]: ['hardware_engineer'], // 硬件设计：硬件工程师
		[ACTIVE_STATUS.HW_DESIGN_REVIEWING]: ['research_manager'], // 硬件审核：研发经理
		[ACTIVE_STATUS.HW_DESIGN_PURCHASING]: ['purchaser'], // 采购打样：采购人员
		[ACTIVE_STATUS.HW_DESIGN_MAKING]: ['sample_team'], // 样品组制样：样品组
		[ACTIVE_STATUS.HW_DESIGN_STORAGE]: ['warehouse_keeper'], // 样品在库：仓库管理员
	},
	
	// 软硬件调试状态权限
	[PROJECT_STATUS.ACTIVE_SW_HW_DEBUG]: {
		'all': ['software_engineer'] // 全部子状态：软件工程师
	},
	
	// 测试验证状态权限
	[PROJECT_STATUS.ACTIVE_TESTING]: {
		[ACTIVE_STATUS.TESTING_IN_PROGRESS]: ['tester'], // 测试中：测试组人员
		[ACTIVE_STATUS.TESTING_NO_TEST]: ['research_manager'], // 无测试审核：研发经理
	},
	
	// 客户确认状态权限
	[PROJECT_STATUS.ACTIVE_CUSTOMER_CONFIRM]: {
		[ACTIVE_STATUS.CUSTOMER_SHIPPING]: ['receptionist'], // 寄样：前台人员
		[ACTIVE_STATUS.CUSTOMER_TESTING]: ['business_staff', 'director'], // 客户测试：业务人员和董事长
		[ACTIVE_STATUS.CUSTOMER_SAMPLE_STORAGE]: ['warehouse_keeper'], // 样品入库：仓库人员
		[ACTIVE_STATUS.CUSTOMER_ARCHIVING]: ['document_controller'], // 归档：文控
		'no_sign_review_manager': ['research_manager'], // 无签样审核-研发经理审核
		'no_sign_review_director': ['director'], // 无签样审核-董事长审核
	},
	
	// 订单准备状态权限
	[PROJECT_STATUS.ACTIVE_ORDER_PREPARATION]: {
		[ACTIVE_STATUS.ORDER_PENDING]: ['business_staff', 'director'], // 待量产：业务人员和董事长
		[ACTIVE_STATUS.ORDER_REVIEWING]: ['director'], // 订单审核：董事长
		[ACTIVE_STATUS.ORDER_DOCS_SENDING]: ['document_controller'], // 文控发送生产资料：文控
		[ACTIVE_STATUS.ORDER_DOCS_SUPPLEMENTING]: ['research_manager', 'software_engineer', 'hardware_engineer'], // 研发补充资料：研发人员
		[ACTIVE_STATUS.ORDER_MEETING]: ['secretary'], // 产前会议：文秘人员
		[ACTIVE_STATUS.ORDER_PREPARATION]: ['secretary'], // 生产准备：文秘人员
	},
	
	// 生产状态权限
	[PROJECT_STATUS.ACTIVE_PRODUCTION]: {
		[ACTIVE_STATUS.PRODUCTION_IN_PROGRESS]: ['production_supervisor'], // 生产中：生产主管
		[ACTIVE_STATUS.PRODUCTION_PE_ISSUE]: ['production_engineer'], // PE问题处理中：PE
		[ACTIVE_STATUS.PRODUCTION_RD_ISSUE]: ['software_engineer'], // 研发问题排查：软件工程师
		[ACTIVE_STATUS.PRODUCTION_COMPLETED]: ['production_supervisor'], // 生产完成：生产主管
	},
	
	// 产品待客户反馈状态权限
	[PROJECT_STATUS.ACTIVE_PRODUCT_FEEDBACK]: {
		'all': ['business_staff', 'director'] // 全部子状态：业务人员和董事长
	},
	
	// 资料同步
	'data_sync': ['research_member', 'research_manager', 'software_engineer'], // 资料同步：研发人员和软件工程师
};

/**
 * 允许的状态流转定义
 */
const ALLOWED_STATE_TRANSITIONS = {
	// 基础状态流转
	[PROJECT_STATUS.PENDING]: [PROJECT_STATUS.REVIEWING],
	[PROJECT_STATUS.REVIEWING]: [PROJECT_STATUS.ACTIVE_HARDWARE_CONFIRM, PROJECT_STATUS.DORMANT],
	[PROJECT_STATUS.DORMANT]: [PROJECT_STATUS.REVIEWING, PROJECT_STATUS.ACTIVE_HARDWARE_CONFIRM],
	[PROJECT_STATUS.ACTIVE]: [PROJECT_STATUS.DORMANT, PROJECT_STATUS.REVIEWING, PROJECT_STATUS.COMPLETED],
	[PROJECT_STATUS.COMPLETED]: [],
	
	// 活动状态内部流转
	[PROJECT_STATUS.ACTIVE_HARDWARE_CONFIRM]: [
		PROJECT_STATUS.ACTIVE_HARDWARE_DESIGN,
		PROJECT_STATUS.ACTIVE_SW_HW_DEBUG,
		PROJECT_STATUS.ACTIVE_PRODUCT_FEEDBACK,
		PROJECT_STATUS.ACTIVE_CUSTOMER_CONFIRM
	],
	[PROJECT_STATUS.ACTIVE_HARDWARE_DESIGN]: [
		PROJECT_STATUS.ACTIVE_SW_HW_DEBUG
	],
	[PROJECT_STATUS.ACTIVE_SW_HW_DEBUG]: [
		PROJECT_STATUS.ACTIVE_HARDWARE_CONFIRM,
		PROJECT_STATUS.ACTIVE_TESTING,
		PROJECT_STATUS.ACTIVE_PRODUCT_FEEDBACK,
		PROJECT_STATUS.ACTIVE_CUSTOMER_CONFIRM
	],
	[PROJECT_STATUS.ACTIVE_TESTING]: [
		PROJECT_STATUS.ACTIVE_SW_HW_DEBUG,
		PROJECT_STATUS.ACTIVE_CUSTOMER_CONFIRM,
		PROJECT_STATUS.ACTIVE_PRODUCT_FEEDBACK
	],
	[PROJECT_STATUS.ACTIVE_CUSTOMER_CONFIRM]: [
		PROJECT_STATUS.ACTIVE_ORDER_PREPARATION,
		PROJECT_STATUS.ACTIVE_SW_HW_DEBUG,
		PROJECT_STATUS.ACTIVE_PRODUCT_FEEDBACK
	],
	[PROJECT_STATUS.ACTIVE_ORDER_PREPARATION]: [
		PROJECT_STATUS.ACTIVE_CUSTOMER_CONFIRM,
		PROJECT_STATUS.ACTIVE_PRODUCTION,
		PROJECT_STATUS.ACTIVE_PRODUCT_FEEDBACK
	],
	[PROJECT_STATUS.ACTIVE_PRODUCTION]: [
		PROJECT_STATUS.ACTIVE_CUSTOMER_CONFIRM,
		PROJECT_STATUS.ACTIVE_PRODUCT_FEEDBACK
	],
	[PROJECT_STATUS.ACTIVE_PRODUCT_FEEDBACK]: [
		PROJECT_STATUS.ACTIVE_ORDER_PREPARATION,
		PROJECT_STATUS.ACTIVE_SW_HW_DEBUG,
		PROJECT_STATUS.COMPLETED
	]
};

/**
 * 状态名称映射
 */
const STATUS_NAMES = {
	[PROJECT_STATUS.PENDING]: '待立项',
	[PROJECT_STATUS.REVIEWING]: '项目审核',
	[PROJECT_STATUS.DORMANT]: '休眠',
	[PROJECT_STATUS.ACTIVE]: '活动',
	[PROJECT_STATUS.COMPLETED]: '完成',
	
	[PROJECT_STATUS.ACTIVE_HARDWARE_CONFIRM]: '硬件确认',
	[PROJECT_STATUS.ACTIVE_HARDWARE_DESIGN]: '硬件设计打样',
	[PROJECT_STATUS.ACTIVE_SW_HW_DEBUG]: '软硬件调试',
	[PROJECT_STATUS.ACTIVE_TESTING]: '测试验证',
	[PROJECT_STATUS.ACTIVE_CUSTOMER_CONFIRM]: '客户确认',
	[PROJECT_STATUS.ACTIVE_ORDER_PREPARATION]: '订单准备',
	[PROJECT_STATUS.ACTIVE_PRODUCTION]: '生产',
	[PROJECT_STATUS.ACTIVE_PRODUCT_FEEDBACK]: '产品待客户反馈',
};

/**
 * 活动子状态名称映射
 */
const ACTIVE_STATUS_NAMES = {
	// 硬件确认子状态
	[PROJECT_STATUS.ACTIVE_HARDWARE_CONFIRM]: {
		[ACTIVE_STATUS.HW_CONFIRM_PENDING]: '待确认',
		[ACTIVE_STATUS.HW_CONFIRM_REVIEWING]: '确认中',
		[ACTIVE_STATUS.HW_CONFIRM_COMPLETED]: '确认完成',
	},
	
	// 硬件设计打样子状态
	[PROJECT_STATUS.ACTIVE_HARDWARE_DESIGN]: {
		[ACTIVE_STATUS.HW_DESIGN_DESIGNING]: '设计中',
		[ACTIVE_STATUS.HW_DESIGN_REVIEWING]: '审核中',
		[ACTIVE_STATUS.HW_DESIGN_PURCHASING]: '采购打样',
		[ACTIVE_STATUS.HW_DESIGN_MAKING]: '制样',
		[ACTIVE_STATUS.HW_DESIGN_STORAGE]: '入库',
	},
	
	// 软硬件调试子状态
	[PROJECT_STATUS.ACTIVE_SW_HW_DEBUG]: {
		[ACTIVE_STATUS.DEBUG_DEBUGGING]: '调试中',
		[ACTIVE_STATUS.DEBUG_ISSUE_FIXING]: '问题修复',
		[ACTIVE_STATUS.DEBUG_COMPLETED]: '调试完成',
	},
	
	// 测试验证子状态
	[PROJECT_STATUS.ACTIVE_TESTING]: {
		[ACTIVE_STATUS.TESTING_IN_PROGRESS]: '测试中',
		[ACTIVE_STATUS.TESTING_NO_TEST]: '无测试申请',
		[ACTIVE_STATUS.TESTING_COMPLETED]: '测试完成',
	},
	
	// 客户确认子状态
	[PROJECT_STATUS.ACTIVE_CUSTOMER_CONFIRM]: {
		[ACTIVE_STATUS.CUSTOMER_SHIPPING]: '寄样',
		[ACTIVE_STATUS.CUSTOMER_TESTING]: '客户测试',
		[ACTIVE_STATUS.CUSTOMER_NO_SIGN]: '无签样审核',
		[ACTIVE_STATUS.CUSTOMER_SAMPLE_STORAGE]: '样品入库',
		[ACTIVE_STATUS.CUSTOMER_ARCHIVING]: '归档',
	},
	
	// 订单准备子状态
	[PROJECT_STATUS.ACTIVE_ORDER_PREPARATION]: {
		[ACTIVE_STATUS.ORDER_PENDING]: '待量产',
		[ACTIVE_STATUS.ORDER_REVIEWING]: '订单审核',
		[ACTIVE_STATUS.ORDER_DOCS_SENDING]: '文控发送生产资料',
		[ACTIVE_STATUS.ORDER_DOCS_SUPPLEMENTING]: '研发补充资料',
		[ACTIVE_STATUS.ORDER_MEETING]: '产前会议',
		[ACTIVE_STATUS.ORDER_PREPARATION]: '生产准备',
	},
	
	// 生产子状态
	[PROJECT_STATUS.ACTIVE_PRODUCTION]: {
		[ACTIVE_STATUS.PRODUCTION_IN_PROGRESS]: '生产中',
		[ACTIVE_STATUS.PRODUCTION_PE_ISSUE]: 'PE问题处理中',
		[ACTIVE_STATUS.PRODUCTION_RD_ISSUE]: '研发问题排查',
		[ACTIVE_STATUS.PRODUCTION_COMPLETED]: '生产完成',
	},
	
	// 产品待客户反馈子状态
	[PROJECT_STATUS.ACTIVE_PRODUCT_FEEDBACK]: {
		[ACTIVE_STATUS.FEEDBACK_PENDING]: '待反馈',
		[ACTIVE_STATUS.FEEDBACK_RECEIVED]: '已收到反馈',
		[ACTIVE_STATUS.FEEDBACK_PROCESSING]: '反馈处理中',
		[ACTIVE_STATUS.FEEDBACK_RESOLVED]: '反馈已解决',
	},
};

/**
 * 获取状态名称
 * @param {Number} status 状态码
 * @returns {String} 状态名称
 */
function getStatusName(status) {
	return STATUS_NAMES[status] || '未知状态';
}

/**
 * 获取活动子状态名称
 * @param {Number} status 状态码
 * @param {Number} activeStatus 活动子状态码
 * @returns {String} 活动子状态名称
 */
function getActiveStatusName(status, activeStatus) {
	if (ACTIVE_STATUS_NAMES[status] && ACTIVE_STATUS_NAMES[status][activeStatus]) {
		return ACTIVE_STATUS_NAMES[status][activeStatus];
	}
	return '未知子状态';
}

/**
 * 检查状态流转是否允许
 * @param {Number} fromStatus 起始状态
 * @param {Number} toStatus 目标状态
 * @returns {Boolean} 是否允许
 */
function isTransitionAllowed(fromStatus, toStatus) {
	// 如果是活动状态，都对应于状态码3
	if (fromStatus >= 10 && fromStatus < 99) {
		fromStatus = PROJECT_STATUS.ACTIVE;
	}
	
	if (toStatus >= 10 && toStatus < 99) {
		// 检查是否允许从当前状态到活动状态
		if (fromStatus !== PROJECT_STATUS.ACTIVE && !ALLOWED_STATE_TRANSITIONS[fromStatus].includes(PROJECT_STATUS.ACTIVE)) {
			return false;
		}
		
		// 如果已经是活动状态，检查具体的子状态流转
		if (fromStatus === PROJECT_STATUS.ACTIVE) {
			// 获取实际的子状态
			const actualFromStatus = fromStatus >= 10 ? fromStatus : PROJECT_STATUS.ACTIVE_HARDWARE_CONFIRM;
			return ALLOWED_STATE_TRANSITIONS[actualFromStatus]?.includes(toStatus) || false;
		}
		
		// 允许从非活动状态进入活动子状态
		return true;
	}
	
	// 基础状态流转检查
	return ALLOWED_STATE_TRANSITIONS[fromStatus]?.includes(toStatus) || false;
}

/**
 * 获取允许的下一个状态列表
 * @param {Number} currentStatus 当前状态
 * @param {Number} currentActiveStatus 当前活动子状态
 * @returns {Array} 允许的下一个状态列表
 */
function getAllowedNextStates(currentStatus, currentActiveStatus) {
	let allowedStates = [];
	
	// 处理活动子状态
	if (currentStatus >= 10 && currentStatus < 99) {
		// 获取活动子状态允许的下一个状态
		allowedStates = [...ALLOWED_STATE_TRANSITIONS[currentStatus] || []];
		
		// 如果是活动子状态的最终状态，允许流转到其他活动子状态或基础状态
		const isCompletedSubstate = 
			(currentStatus === PROJECT_STATUS.ACTIVE_HARDWARE_CONFIRM && currentActiveStatus === ACTIVE_STATUS.HW_CONFIRM_COMPLETED) ||
			(currentStatus === PROJECT_STATUS.ACTIVE_HARDWARE_DESIGN && currentActiveStatus === ACTIVE_STATUS.HW_DESIGN_STORAGE) ||
			(currentStatus === PROJECT_STATUS.ACTIVE_SW_HW_DEBUG && currentActiveStatus === ACTIVE_STATUS.DEBUG_COMPLETED) ||
			(currentStatus === PROJECT_STATUS.ACTIVE_TESTING && currentActiveStatus === ACTIVE_STATUS.TESTING_COMPLETED) ||
			(currentStatus === PROJECT_STATUS.ACTIVE_CUSTOMER_CONFIRM && currentActiveStatus === ACTIVE_STATUS.CUSTOMER_ARCHIVING) ||
			(currentStatus === PROJECT_STATUS.ACTIVE_ORDER_PREPARATION && currentActiveStatus === ACTIVE_STATUS.ORDER_PREPARATION) ||
			(currentStatus === PROJECT_STATUS.ACTIVE_PRODUCTION && currentActiveStatus === ACTIVE_STATUS.PRODUCTION_COMPLETED) ||
			(currentStatus === PROJECT_STATUS.ACTIVE_PRODUCT_FEEDBACK && currentActiveStatus === ACTIVE_STATUS.FEEDBACK_RESOLVED);
		
		if (isCompletedSubstate) {
			// 允许流转到基础状态
			allowedStates.push(PROJECT_STATUS.DORMANT);
			allowedStates.push(PROJECT_STATUS.REVIEWING);
			allowedStates.push(PROJECT_STATUS.COMPLETED);
		}
	} else {
		// 基础状态流转
		allowedStates = [...ALLOWED_STATE_TRANSITIONS[currentStatus] || []];
		
		// 如果当前是活动状态，添加所有活动子状态
		if (currentStatus === PROJECT_STATUS.ACTIVE) {
			allowedStates.push(
				PROJECT_STATUS.ACTIVE_HARDWARE_CONFIRM,
				PROJECT_STATUS.ACTIVE_HARDWARE_DESIGN,
				PROJECT_STATUS.ACTIVE_SW_HW_DEBUG,
				PROJECT_STATUS.ACTIVE_TESTING,
				PROJECT_STATUS.ACTIVE_CUSTOMER_CONFIRM,
				PROJECT_STATUS.ACTIVE_ORDER_PREPARATION,
				PROJECT_STATUS.ACTIVE_PRODUCTION,
				PROJECT_STATUS.ACTIVE_PRODUCT_FEEDBACK
			);
		}
	}
	
	return allowedStates;
}

/**
 * 获取状态流转结构化数据
 * @param {Number} currentStatus 当前状态
 * @param {Number} currentActiveStatus 当前活动子状态
 * @returns {Array} 状态流转结构化数据
 */
function getStateTransitionStructure(currentStatus, currentActiveStatus) {
	const allowedStates = getAllowedNextStates(currentStatus, currentActiveStatus);
	
	return allowedStates.map(status => {
		const isActiveState = status >= 10 && status < 99;
		const data = {
			status: status,
			name: getStatusName(status),
			isActive: isActiveState,
			subStates: []
		};
		
		// 如果是活动子状态，添加子状态数据
		if (isActiveState && ACTIVE_STATUS_NAMES[status]) {
			Object.entries(ACTIVE_STATUS_NAMES[status]).forEach(([subStatus, name]) => {
				data.subStates.push({
					status: parseInt(subStatus),
					name: name
				});
			});
		}
		
		return data;
	});
}

/**
 * 流转项目状态
 * @param {String} projectId 项目ID
 * @param {Number} toStatus 目标状态
 * @param {Number} toActiveStatus 目标活动子状态
 * @param {Object} flowData 流转数据
 * @returns {Promise} 异步结果
 */
async function transitProjectState(projectId, toStatus, toActiveStatus, flowData = {}) {
	if (!projectId) return { code: -1, message: '项目ID不能为空' };
	
	try {
		// 获取项目详情
		const service = new ResearchService();
		const project = await service.getResearchDetail(projectId);
		
		if (!project) {
			return { code: -1, message: '项目不存在' };
		}
		
		// 获取当前状态
		const currentStatus = project.PROJECT_STATUS || 0;
		const currentActiveStatus = project.PROJECT_ACTIVE_STATUS || 0;
		
		// 检查状态流转是否允许
		if (!isTransitionAllowed(currentStatus, toStatus)) {
			return { 
				code: -1, 
				message: `状态流转不允许: ${getStatusName(currentStatus)} -> ${getStatusName(toStatus)}` 
			};
		}
		
		// 构建流转数据
		const data = {
			note: flowData.note || '',
			docs: flowData.docs || [],
			tags: flowData.tags || []
		};
		
		// 更新项目状态
		const result = await service.updateResearchStatus(projectId, toStatus, toActiveStatus, data);
		
		if (!result) {
			return { code: -1, message: '状态更新失败' };
		}

		// 状态流转成功后，创建关联任务
		try {
			// 获取当前用户ID（来自流转数据或当前用户）
			const userId = flowData.userId || project.PROJECT_MANAGER_ID || '';
			
			// 创建任务
			await FlowTaskBiz.createTasksForProjectStatus(projectId, toStatus, toActiveStatus, userId);
			
			console.log(`[ResearchStateBiz] 项目 ${projectId} 状态流转触发任务创建成功`);
		} catch (taskErr) {
			console.error('[ResearchStateBiz] 状态流转后创建任务失败', taskErr);
			// 任务创建失败不影响状态流转结果
		}
		
		return { code: 0, message: '状态更新成功' };
	} catch (err) {
		console.error('项目状态流转失败', err);
		return { code: -1, message: '状态流转失败' };
	}
}

/**
 * 获取项目状态统计
 * @param {Array} projects 项目列表
 * @returns {Object} 状态统计
 */
function getProjectStatusStats(projects) {
	if (!projects || !Array.isArray(projects)) {
		return {};
	}
	
	const stats = {
		total: projects.length,
		pending: 0,
		reviewing: 0,
		active: 0,
		dormant: 0,
		completed: 0,
		activeStates: {}
	};
	
	// 初始化活动子状态统计
	Object.keys(STATUS_NAMES).forEach(key => {
		const status = parseInt(key);
		if (status >= 10 && status < 99) {
			stats.activeStates[status] = 0;
		}
	});
	
	// 统计各状态数量
	projects.forEach(project => {
		const status = project.PROJECT_STATUS || 0;
		
		if (status === PROJECT_STATUS.PENDING) {
			stats.pending++;
		} else if (status === PROJECT_STATUS.REVIEWING) {
			stats.reviewing++;
		} else if (status === PROJECT_STATUS.DORMANT) {
			stats.dormant++;
		} else if (status === PROJECT_STATUS.COMPLETED) {
			stats.completed++;
		} else if (status === PROJECT_STATUS.ACTIVE || (status >= 10 && status < 99)) {
			stats.active++;
			
			// 如果是活动子状态，统计子状态数量
			if (status >= 10 && status < 99) {
				stats.activeStates[status] = (stats.activeStates[status] || 0) + 1;
			}
		}
	});
	
	return stats;
}

/**
 * 将模型层状态码映射到业务逻辑层状态码
 * @param {Number} modelStatus 模型层状态码
 * @returns {Number} 业务逻辑层状态码
 */
function mapModelStatusToBizStatus(modelStatus) {
	console.log('[状态映射] 映射模型状态码:', modelStatus);
	
	// 模型层状态码与业务逻辑层状态码的映射关系
	const statusMap = {
		1: PROJECT_STATUS.PENDING,        // 待立项 -> PENDING
		2: PROJECT_STATUS.REVIEWING,      // 项目审核 -> REVIEWING
		3: PROJECT_STATUS.DORMANT,        // 休眠 -> DORMANT
		4: PROJECT_STATUS.ACTIVE          // 活动 -> ACTIVE
	};
	
	// 如果是活动子状态编码(大于10)，直接返回
	if (modelStatus >= 10) {
		return modelStatus;
	}
	
	const mappedStatus = statusMap[modelStatus] !== undefined ? statusMap[modelStatus] : modelStatus;
	console.log('[状态映射] 映射结果:', { original: modelStatus, mapped: mappedStatus });
	return mappedStatus;
}

/**
 * 将模型层子状态码映射到业务逻辑层子状态码
 * @param {Number} modelStatus 模型层主状态码
 * @param {Number} modelSubStatus 模型层子状态码
 * @returns {Number} 业务逻辑层子状态码
 */
function mapModelSubStatusToBizSubStatus(modelStatus, modelSubStatus) {
	console.log('[状态映射] 映射子状态码:', { modelStatus, modelSubStatus });
	
	// 不同主状态下的子状态映射
	if (modelStatus === 2) { // 项目审核状态
		// 映射项目审核子状态
		const subStatusMap = {
			1: ACTIVE_STATUS.REVIEW_DIRECTOR, // 待董事长审核
			2: ACTIVE_STATUS.REVIEW_MANAGER,  // 待研发经理审核
			3: ACTIVE_STATUS.REVIEW_ASSIGN    // 项目分配
		};
		const mappedSubStatus = subStatusMap[modelSubStatus] !== undefined ? subStatusMap[modelSubStatus] : modelSubStatus;
		console.log('[状态映射] 审核子状态映射结果:', { original: modelSubStatus, mapped: mappedSubStatus });
		return mappedSubStatus;
	}
	
	if (modelStatus === 3) { // 休眠状态
		// 映射休眠子状态
		const subStatusMap = {
			1: ACTIVE_STATUS.DORMANT_REVIEW,  // 研发审核
			2: ACTIVE_STATUS.DORMANT_ARCHIVE  // 休眠归档
		};
		const mappedSubStatus = subStatusMap[modelSubStatus] !== undefined ? subStatusMap[modelSubStatus] : modelSubStatus;
		console.log('[状态映射] 休眠子状态映射结果:', { original: modelSubStatus, mapped: mappedSubStatus });
		return mappedSubStatus;
	}
	
	// 返回原始子状态码
	return modelSubStatus;
}

/**
 * 检查状态权限
 * @param {Number} status 状态
 * @param {Number} subStatus 子状态
 * @param {String} statusDesc 状态描述
 * @param {Array} userRoles 用户角色
 * @param {Object} options 选项
 * @returns {Object} 权限检查结果
 */
function checkStatusPermission(status, subStatus, statusDesc, userRoles, options = {}) {
	console.log('[权限检查] 开始检查权限:', { status, subStatus, statusDesc, userRoles, options });
	
	// 特殊处理：硬件确认状态与硬件工程师角色
	if ((status === 10 || (statusDesc && statusDesc.includes('硬件确认'))) && 
	    userRoles.some(role => role === 'hardware_engineer') || 
	    (options.simulatedRole === 'hardware_engineer')) {
		console.log('[权限检查] 硬件工程师特权: 授予硬件确认状态权限');
		return { 
			hasPermission: true, 
			reason: '硬件工程师具有硬件确认状态的特殊权限',
			isSimulated: options.simulatedRole ? true : false
		};
	}
	
	// 进行状态码映射
	const mappedStatus = mapModelStatusToBizStatus(status);
	const mappedSubStatus = mapModelSubStatusToBizSubStatus(status, subStatus);
	
	console.log('[权限检查] 状态映射结果:', { 
		originalStatus: status, 
		mappedStatus: mappedStatus, 
		originalSubStatus: subStatus, 
		mappedSubStatus: mappedSubStatus
	});
	
	// 使用映射后的状态码进行后续权限检查
	status = mappedStatus;
	subStatus = mappedSubStatus;
	
	// 处理角色模拟逻辑
	const simulationInfo = handleRoleSimulation(userRoles, options);
	const effectiveRoles = simulationInfo.effectiveRoles || userRoles;
	let permissionResult = { hasPermission: false, reason: '无法确定状态权限' };
	
	console.log('[权限检查] 有效角色:', effectiveRoles);
	
	// 管理员、项目经理和研发经理有全部权限
	if (effectiveRoles.includes('admin') || effectiveRoles.includes('project_manager') || effectiveRoles.includes('research_manager')) {
		permissionResult = { 
			hasPermission: true, 
			reason: '管理员/项目经理/研发经理拥有完全流转权限',
			isSimulated: simulationInfo.isSimulated
		};
		console.log('[权限检查] 管理员/项目经理/研发经理特权授权');
		return permissionResult;
	}
	
	// 检查特定状态的权限
	if (STATUS_ROLE_PERMISSIONS[status]) {
		console.log('[权限检查] 检查状态特定权限:', { 
			status, 
			subStatus, 
			availablePermissions: STATUS_ROLE_PERMISSIONS[status]
		});
		
		// 检查子状态权限
		if (STATUS_ROLE_PERMISSIONS[status][subStatus]) {
			const allowedRoles = STATUS_ROLE_PERMISSIONS[status][subStatus];
			console.log('[权限检查] 子状态权限定义:', { subStatus, allowedRoles });
			
			const hasRole = allowedRoles.some(role => effectiveRoles.includes(role));
			if (hasRole) {
				permissionResult = { 
					hasPermission: true, 
					reason: '用户具有所需角色权限',
					isSimulated: simulationInfo.isSimulated
				};
				console.log('[权限检查] 用户拥有子状态所需角色');
				return permissionResult;
			}
			permissionResult = { 
				hasPermission: false, 
				reason: `只有${allowedRoles.join('、')}可以流转此状态`,
				isSimulated: simulationInfo.isSimulated
			};
			console.log('[权限检查] 用户不具备子状态所需角色');
			return permissionResult;
		}
		
		// 检查该状态的通用权限
		if (STATUS_ROLE_PERMISSIONS[status]['all']) {
			const allowedRoles = STATUS_ROLE_PERMISSIONS[status]['all'];
			console.log('[权限检查] 状态通用权限定义:', { status, allowedRoles });
			
			const hasRole = allowedRoles.some(role => effectiveRoles.includes(role));
			if (hasRole) {
				permissionResult = { 
					hasPermission: true, 
					reason: '用户具有所需角色权限',
					isSimulated: simulationInfo.isSimulated
				};
				console.log('[权限检查] 用户拥有状态通用所需角色');
				return permissionResult;
			}
			permissionResult = { 
				hasPermission: false, 
				reason: `只有${allowedRoles.join('、')}可以流转此状态`,
				isSimulated: simulationInfo.isSimulated
			};
			console.log('[权限检查] 用户不具备状态通用所需角色');
			return permissionResult;
		}
	}
	
	// 特殊状态检查（基于状态描述）
	if (statusDesc) {
		const lowerDesc = statusDesc.toLowerCase();
		
		// 无签样审核-研发经理审核
		if (lowerDesc.includes('无签样审核') && lowerDesc.includes('研发经理审核')) {
			const allowedRoles = STATUS_ROLE_PERMISSIONS[PROJECT_STATUS.ACTIVE_CUSTOMER_CONFIRM]['no_sign_review_manager'];
			const hasRole = allowedRoles.some(role => effectiveRoles.includes(role));
			if (hasRole) {
				permissionResult = { 
					hasPermission: true, 
					reason: '用户具有所需角色权限',
					isSimulated: simulationInfo.isSimulated
				};
				return permissionResult;
			}
			permissionResult = { 
				hasPermission: false, 
				reason: '只有研发经理可以流转此状态',
				isSimulated: simulationInfo.isSimulated
			};
			return permissionResult;
		}
		
		// 无签样审核-董事长审核
		if (lowerDesc.includes('无签样审核') && lowerDesc.includes('董事长审核')) {
			const allowedRoles = STATUS_ROLE_PERMISSIONS[PROJECT_STATUS.ACTIVE_CUSTOMER_CONFIRM]['no_sign_review_director'];
			const hasRole = allowedRoles.some(role => effectiveRoles.includes(role));
			if (hasRole) {
				permissionResult = { 
					hasPermission: true, 
					reason: '用户具有所需角色权限',
					isSimulated: simulationInfo.isSimulated
				};
				return permissionResult;
			}
			permissionResult = { 
				hasPermission: false, 
				reason: '只有董事长可以流转此状态',
				isSimulated: simulationInfo.isSimulated
			};
			return permissionResult;
		}
		
		// 资料同步
		if (lowerDesc.includes('资料同步')) {
			const allowedRoles = STATUS_ROLE_PERMISSIONS['data_sync'];
			const hasRole = allowedRoles.some(role => effectiveRoles.includes(role));
			if (hasRole) {
				permissionResult = { 
					hasPermission: true, 
					reason: '用户具有所需角色权限',
					isSimulated: simulationInfo.isSimulated
				};
				return permissionResult;
			}
			permissionResult = { 
				hasPermission: false, 
				reason: '只有研发人员可以流转此状态',
				isSimulated: simulationInfo.isSimulated
			};
			return permissionResult;
		}
		
		// 待董事长审核状态 - 通过描述文本匹配
		if (lowerDesc.includes('待董事长审核') || lowerDesc.includes('董事长审核')) {
			console.log('[权限检查] 检测到通过描述匹配的董事长审核状态');
			const allowedRoles = ['director']; // 只允许董事长角色
			const hasRole = allowedRoles.some(role => effectiveRoles.includes(role));
			if (hasRole) {
				permissionResult = { 
					hasPermission: true, 
					reason: '用户具有董事长角色权限',
					isSimulated: simulationInfo.isSimulated
				};
				console.log('[权限检查] 用户具有董事长角色权限');
				return permissionResult;
			}
			permissionResult = { 
				hasPermission: false, 
				reason: '只有董事长可以流转此状态',
				isSimulated: simulationInfo.isSimulated
			};
			console.log('[权限检查] 用户不具备董事长角色');
			return permissionResult;
		}
	}
	
	// 默认情况下不授予权限
	permissionResult = { 
		hasPermission: false, 
		reason: '无法确定状态权限',
		isSimulated: simulationInfo.isSimulated
	};
	return permissionResult;
}

/**
 * 处理角色模拟逻辑
 * @param {Array} userRoles 用户实际角色列表
 * @param {Object} options 选项，包含模拟角色信息
 * @returns {Object} 处理结果，包含有效角色和是否模拟的标志
 */
function handleRoleSimulation(userRoles, options = {}) {
	console.log('[角色模拟] 处理开始:', { userRoles, options, ROLE_SIMULATION });
	
	const result = {
		effectiveRoles: [...userRoles],
		isSimulated: false,
		simulatedRole: null
	};

	// 检查是否启用了角色模拟
	if (!options.simulatedRole || !ROLE_SIMULATION.ENABLED) {
		console.log('[角色模拟] 未启用或无模拟角色:', { 
			simulatedRole: options.simulatedRole, 
			enabled: ROLE_SIMULATION.ENABLED 
		});
		return result;
	}

	// 检查是否仅限管理员使用模拟功能
	if (ROLE_SIMULATION.ADMIN_ONLY && !userRoles.includes('admin')) {
		console.log('[角色模拟] 非管理员无法使用模拟功能');
		return result;
	}

	// 检查模拟的角色是否在允许列表中
	if (!ROLE_SIMULATION.ALLOWED_ROLES.includes(options.simulatedRole)) {
		console.warn(`[角色模拟] 尝试模拟未授权的角色: ${options.simulatedRole}`);
		return result;
	}

	// 记录模拟操作日志
	if (ROLE_SIMULATION.LOG_ACTIONS) {
		console.log(`[角色模拟] 用户角色 ${userRoles.join(',')} 模拟角色 ${options.simulatedRole}`);
		// 这里可以添加更详细的日志记录，如时间戳、项目ID等
		logRoleSimulation(userRoles, options.simulatedRole, options.projectId);
	}

	// 返回带有模拟角色的结果
	result.effectiveRoles = [options.simulatedRole];
	result.isSimulated = true;
	result.simulatedRole = options.simulatedRole;
	
	console.log('[角色模拟] 处理完成，返回结果:', result);
	return result;
}

/**
 * 记录角色模拟操作日志
 * @param {Array} userRoles 用户实际角色
 * @param {String} simulatedRole 模拟角色
 * @param {String} projectId 项目ID
 */
async function logRoleSimulation(userRoles, simulatedRole, projectId) {
	try {
		const logData = {
			type: 'ROLE_SIMULATION',
			userRoles: userRoles,
			simulatedRole: simulatedRole,
			projectId: projectId || '',
			timestamp: dayjs().valueOf()
		};

		// 调用云函数记录日志
		await cloudHelper.callCloud('log/add', {
			logType: 'ROLE_SIMULATION',
			content: JSON.stringify(logData)
		});
	} catch (error) {
		console.error('[角色模拟] 记录日志失败', error);
	}
}

/**
 * 设置角色模拟全局开关
 * @param {Boolean} enabled 是否启用
 * @param {Array} userRoles 当前用户角色，用于权限检查
 * @returns {Boolean} 设置是否成功
 */
function setRoleSimulationEnabled(enabled, userRoles = []) {
	// 移除权限检查，允许任何用户设置
	/*
	// 检查权限，仅管理员可设置
	if (!userRoles.includes('admin')) {
		console.warn('[角色模拟] 非管理员尝试修改模拟设置');
		return false;
	}
	*/
	
	ROLE_SIMULATION.ENABLED = !!enabled;
	console.log(`[角色模拟] ${enabled ? '启用' : '禁用'}角色模拟功能`);
	return true;
}

/**
 * 获取角色模拟配置
 * @param {Array} userRoles 当前用户角色，用于权限检查
 * @returns {Object|null} 角色模拟配置或null（无权限）
 */
function getRoleSimulationConfig(userRoles = []) {
	// 检查权限，仅管理员可查看完整配置
	if (!userRoles.includes('admin')) {
		return {
			enabled: ROLE_SIMULATION.ENABLED,
			allowedRoles: ROLE_SIMULATION.ALLOWED_ROLES
		};
	}
	
	return { ...ROLE_SIMULATION };
}

/**
 * 权限检查函数
 * @param {String} targetRole 目标角色
 * @param {Object} options 选项
 * @returns {Boolean} 是否有权限
 */
function hasPermission(targetRole, options = {}) {
	// 获取当前用户角色
	let currentRole = '';

	// 优先使用角色模拟系统的设置
	const mockRole = projectHelpers.testHelper ? projectHelpers.testHelper.getCurrentRole() : null;
	if (mockRole) {
		currentRole = mockRole;
	} else {
		// 未开启模拟则使用用户实际角色
		currentRole = getRole();
	}

	// 特殊情况：管理员拥有所有权限
	if (currentRole === 'admin') return true;

	// 特殊情况：研发主管可执行任何研发角色操作
	if (currentRole === 'director' && options.allowDirector !== false) return true;

	// 特殊情况：研发经理可执行大部分研发角色操作
	if (currentRole === 'research_manager' && options.allowManager !== false) {
		// 例外：研发经理不能执行仓库和样品组的操作
		if (['warehouse', 'sample_group'].includes(targetRole)) return false;
		return true;
	}

	// 普通情况：角色匹配
	return currentRole === targetRole;
}

// 检查角色是否有事件操作权限
function hasEventPermission(roleId, eventCode) {
	return roleConfig.hasEventPermission(roleId, eventCode);
}

// 获取用户可用的事件
function getAvailableEvents(currentStatus, userRole) {
	if (!currentStatus || !userRole) {
		return [];
	}

	// 获取当前状态下的所有事件
	const allEvents = ResearchStateMachine.getEventsByStatus(currentStatus);
	
	// 过滤用户有权限的事件
	return allEvents.filter(event => hasEventPermission(userRole, event.code));
}

// 获取状态机当前状态的层级结构
function getStatusHierarchy(status) {
	if (!status) return null;
	
	// 分割状态（如果有子状态）
	const parts = status.split('.');
	const mainStatus = parts[0];
	const subStatus = parts.length > 1 ? parts[1] : null;
	
	return {
		mainStatus,
		subStatus,
		fullStatus: status
	};
}

module.exports = {
	PROJECT_STATUS,
	ACTIVE_STATUS,
	STATUS_NAMES,
	ACTIVE_STATUS_NAMES,
	STATUS_ROLE_PERMISSIONS,
	ROLE_SIMULATION,
	getStatusName,
	getActiveStatusName,
	isTransitionAllowed,
	getAllowedNextStates,
	getStateTransitionStructure,
	transitProjectState,
	getProjectStatusStats,
	checkStatusPermission,
	setRoleSimulationEnabled,
	getRoleSimulationConfig,
	hasPermission,
	mapModelStatusToBizStatus,
	mapModelSubStatusToBizSubStatus,
	hasEventPermission,
	getAvailableEvents,
	getStatusHierarchy
}; 